package com.bqmart.tool.web.controller;

import com.aliyun.openservices.ons.api.Action;
import com.bqmart.tool.web.form.MessageInfo;
import com.bruce.tool.common.util.LogUtils;
import com.bruce.tool.mq.aliyun.core.AliReceiver;
import com.bruce.tool.mq.aliyun.core.AliSender;
import com.bruce.tool.mq.aliyun.domain.AliMessage;
import com.bruce.tool.mq.aliyun.domain.AliResponse;
import com.bruce.tool.mq.aliyun.handler.AliMqHandler;
import com.bruce.tool.web.filter.annotation.BlockWaiting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

/**
 * 功能 :
 *
 * @author : Bruce(刘正航) 16:53 2019-02-14
 */
@Slf4j
@Controller
@RequestMapping("/mq")
public class MQController {

    @Autowired
    private AliSender aliSender;

    @Autowired
    private AliReceiver aliReceiver;

    @ResponseBody
    @BlockWaiting(message = "消息发送中,请耐心等待......")
    @RequestMapping(value = "/sendMQ" ,method = RequestMethod.POST)
    public void sendMQ(@Valid @ModelAttribute MessageInfo info){
        AliMessage message = AliMessage.builder().code("111").body("测试消息体".getBytes()).build();
        try {
            Thread.sleep(1000 * 30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        aliSender.execute(message);
    }

    @ResponseBody
    @RequestMapping(value = "/receiveMQ" ,method = RequestMethod.POST)
    public void receiveMQ(){
        aliReceiver.execute("111", new AliMqHandler() {
            @Override
            public Action handle(AliResponse response) {
                String message = new String(response.getBody());
                LogUtils.info(log,message);
                return Action.CommitMessage;
            }
        });
    }
}
